package com.cy.jt.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.cy.jt.mapper.ItemCatParamMapper;
import com.cy.jt.mapper.ItemDescMapper;
import com.cy.jt.mapper.ItemMapper;
import com.cy.jt.pojo.Item;
import com.cy.jt.pojo.ItemDesc;
import com.cy.jt.pojo.ItemParam;
import com.cy.jt.vo.ItemParamVO;
import com.cy.jt.vo.ItemVO;
import com.cy.jt.vo.PageResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.List;

/**
 * @description:
 * @author: LiuXingYu
 * @date: 2021/8/8 11:02
 */
@Service
public class ItemServiceImpl implements ItemService{

    @Autowired
    private ItemMapper itemMapper;
    @Autowired
    private ItemDescMapper itemDescMapper;
    @Autowired
    private ItemCatParamMapper itemCatParamMapper;

    @Override
    public PageResult getItemList(PageResult pageResult) {

        Page<Item> page = new Page<>(pageResult.getPageNum(), pageResult.getPageSize());
        QueryWrapper<Item> queryWrapper = new QueryWrapper<>();
        String query = pageResult.getQuery();
        boolean queryFlag = false;
        if (StringUtils.hasLength(query)){
            queryFlag = true;
        }
        queryWrapper.like(queryFlag, "title", query);
        page = itemMapper.selectPage(page, queryWrapper);
        long total = page.getTotal();
        List<Item> items = page.getRecords();
        return pageResult.setTotal(total).setRows(items);
    }

    @Override
    public void updateItemStatus(Item item) {
        itemMapper.updateById(item);
    }

    @Override
    public void deleteItemById(Integer id) {
        itemMapper.deleteById(id);
    }

    /**
     * 实现三张表入库
     */
    @Override
    @Transactional
    public void saveItem(ItemVO itemVO) {
        // 1.入库商品表
        Item item = itemVO.getItem();
        item.setStatus(true); //默认启用状态
        //要求入库之后返回主键
        //MP如果设定了主键自增则会自动的实现数据回显
        itemMapper.insert(item);

        //2.入库商品详情
        ItemDesc itemDesc = itemVO.getItemDesc();
        itemDescMapper.insert(itemDesc);

        /*//3.入库商品参数
        ItemParam itemParam = itemVO.getItemParam();
        ItemParamVO[] dynamicArray = itemParam.getDynamicArray();
        ItemParamVO[] staticArray = itemParam.getStaticArray();
        //将页面传递的数据转化为JSON,之后数据库保存
        MAPPER.writeValueAsString(dynamic);*/
    }
}
